<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button
            v-allow="'import'"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            v-allow="'export_excel'"
            type="danger"
            size="small"
            @click="handleDownload"
          >excel导出</el-button>
          <el-button
            v-allow="'add'"
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table
          border
          :data="list"
          :default-sort="{ prop: 'timeOfEntry', order: 'ascending' }"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{ row }">
              <img
                :src="row.staffPhoto"
                alt=""
                style="width: 100px; height: 100px"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template #default="{ row }">
              {{ hireTypeFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button
                type="text"
                size="small"
                @click="hAssignRole(row.id)"
              >分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDel(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="400"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工弹层 -->
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
        <empDialog
          ref="empDialog"
          @success="hSuccess"
          @close="showDialog = false"
        />
      </el-dialog>
      <!-- 分配角色弹层 -->
      <el-dialog title="分配角色" :visible.sync="roleShowDialog">
        <!-- v-if="roleShowDialog" 解决数据不更新问题 -->
        <AssignRole
          v-if="roleShowDialog"
          :role-id="roleId"
          @close="roleShowDialog = false"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AssignRole from './components/assignRole'
import { getEmployees, delEmployee } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import empDialog from './empDialog'
// 获取聘用形式的状态两种方法
// const hireType = {}
// employeesEnum.hireType.forEach(item=>{
//   hireType[item.id] = item.value
// })
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    empDialog,
    AssignRole
  },
  data() {
    return {
      roleId: '',
      roleShowDialog: false,
      showDialog: false,
      list: [],
      page: 1, // 页码
      size: 2, // 每页显示的条
      total: 0 // 保存员工信息
    }
  },
  created() {
    this.loadEmployees()
  },

  methods: {
    hAssignRole(id) {
      this.roleId = id
      this.roleShowDialog = true
    },
    dataFormat(list) {
      const mapInfo = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      // 获取表头数据
      const one = list[0]
      let headers = []
      if (one) {
        headers = Object.keys(one).map((enkey) => {
          return mapInfo[enkey]
        })
      }
      // 将每一个对象对象中的值存到一个数组中,将每个数组存储到大数组中
      const data = list.map((item) => {
        return Object.values(item)
      })
      return { headers, data }
    },
    async handleDownload() {
      // 1.发送请求获取数据
      try {
        const res = await getEmployees(this.page, this.size)
        if (res.code !== 10000) return
        console.log(res.data.rows, 'res.data.rows')
        // 2.需要将获取的数据转为excel的格式
        const { headers, data } = this.dataFormat(res.data.rows)
        // 3.调用excel 存入excel文件
        //  import('@/vendor/Export2Excel')  懒加载的方式读取一个文件（模块）返回是一个promise实例对象
        import('@/vendor/Export2Excel').then((excel) => {
          // excel指的是模块对象(文件对象)，就可以直接调用文件中的任何函数或者使用文件中的任何变量  excel.函数名()   || excel.变量
          console.log(excel, 'excel')
          //  excel调用export_json_to_excel()
          excel.export_json_to_excel({
            header: headers,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 实现删除员工
    hDel(id) {
      this.$confirm('删?')
        .then(async() => {
          const res = await delEmployee(id)
          console.log('delEmployee', res)
          // 处理删除没有当页没有数据的情况
          if (this.list.length === 1) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
          this.loadEmployees()
        })
        .catch((err) => err)
    },
    hClose() {
      this.$refs.empDialog.resetForm()
    },
    hSuccess() {
      // 获取到最大页面值
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployees()
      this.showDialog = false
    },
    // 页码
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployees()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployees()
    },
    // 返回的是 正式或者是非正式
    hireTypeFormat(data) {
      // return employeesEnum.hireType.find(item => item.id === data).value
      return hireType[data] || '未知'
    },
    // 获取员工数据
    async loadEmployees() {
      try {
        const res = await getEmployees(this.page, this.size)
        if (res.code === 10000) {
          this.list = res.data.rows
          this.total = res.data.total
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.page-tools {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .tips {
    line-height: 34px;
    padding: 0px 15px;
    border-radius: 5px;
    border: 1px solid rgba(145, 213, 255, 1);
    background: rgba(230, 247, 255, 1);
    i {
      margin-right: 10px;
      color: #409eff;
    }
  }
}
</style>
